package DAO.MysqlDAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import DAO.InterfaceDAO.CourDAO;
import Factories.FactoryMySqlDAO;
import Model.Cour;

public class CourDAO_Mysql implements CourDAO{

	private PreparedStatement psCreate, psRead, psUpdate, psDelete, psFind;

	public CourDAO_Mysql(Connection cx) {

		try {
			psCreate = cx.prepareStatement("INSERT INTO cours VALUES( ?, ?, ?, ?, ?)");
			psRead   = cx.prepareStatement("SELECT * FROM cours WHERE id = ?");
			psUpdate = cx.prepareStatement("UPDATE cours SET titre=?, theme=?, type=?, library=?, auteur=? WHERE id = ? ");
			psDelete = cx.prepareStatement("DELETE FROM cours WHERE id = ?");
			psFind   = cx.prepareStatement("SELECT * FROM cours");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean create(Cour c) {
		boolean rs=false;
		try {
			psCreate.setString(1, c.getTitre());
			psCreate.setString(2, c.getTheme());
			psCreate.setString(3, c.getType());
			psCreate.setString(4, c.getLibrary());
			int id = FactoryMySqlDAO.getInstance().createProfDAO().id(c.getNomAuteur(), c.getPrenomAuteur());
			psCreate.setInt(5, id);
			psCreate.executeUpdate ();
			rs = true;
		} catch (SQLException e) {
			e.printStackTrace();
		}		
		return rs;
	}

	@Override
	public Cour read(int id) {
		try {
			psRead.setInt(1, id);
			ResultSet rs = psRead.executeQuery();	
			String titre = rs.getString(2);
			String type = rs.getString(3);
			String theme = rs.getString(4);
			String library = rs.getString(5);
			String nomAuteur = rs.getString(6);
			String prenomAuteur = rs.getString(7);
			return new Cour(id, titre, type, theme, library, nomAuteur, prenomAuteur);
		} catch (SQLException e) {
			e.printStackTrace();
		}		
		return null;
	}

	@Override
	public boolean update(Cour c) {
		boolean rs=false;
		try {
			psUpdate.setString(1, c.getTitre());
			psUpdate.setString (2, c.getTheme());
			psUpdate.setString (2, c.getType());
			psUpdate.setString (2, c.getLibrary());
			psUpdate.setInt(2, c.getId());
			psUpdate.executeUpdate ();
			rs = true;
		} catch (SQLException e) {
			e.printStackTrace();
		}		
		return rs;
	}

	@Override
	public boolean delete(Cour c) {
		boolean rs=false;
		try {
			psDelete.setInt(1, c.getId());
			psDelete.executeUpdate ();
			rs = true;
		} catch (SQLException e) {
			e.printStackTrace();
		}		
		return rs;
	}

}
